/* Author: Antonio Stoilkov
*/

/// <reference path="libs/jquery-1.6.2-vsdoc.js" />

$(function () {
    $("#login").click(function () {

    });

    var globalAnimationSpeed = 1000;
    var dateAnimationSpeed = 500;

    $("#loading").css("display", "none");

    var userId = getCookie("UserId");

    if (userId != null) {
        login(userId, true);
    } else {
        logout(true);
    }

    $("#loginFailed").slideUp(0);

    var AcademySystemService = (function () {
        /* PRIVATE FIELDS */
        var serviceUrl = "../AcademySystemService.svc/";
        var eventHandlers = ["error"];

        /* PUBLIC */
        var _service = new Object();
        _service.timeout = 5000;
        _service.error = function (errorEventHandler) {
            eventHandlers["error"] = errorEventHandler;
        }

        _service.Cource = function (id, title, information, subscribersCount, startDay, startMonth, endDay, endMonth) {
            this.id = id;
            this.title = HtmlEncoder.htmlEncode(title);
            this.information = HtmlEncoder.htmlEncode(information);
            this.subscribersCount = subscribersCount;
            this.startDay = startDay;
            this.startMonth = startMonth;
            this.endDay = endDay;
            this.endMonth = endMonth;
            this.toString = function () {
                var courseData = "";
                courseData += "<article id='";
                courseData += this.id;
                courseData += "'><h3><span class='title' title='";
                courseData += this.title;
                courseData += "'>";
                var maxTitleLength = 33;
                var shortTitle = this.title;
                if (shortTitle.length > maxTitleLength) {
                    shortTitle = shortTitle.substring(0, maxTitleLength);
                    shortTitle += "...";
                }
                courseData += shortTitle;
                courseData += "</span><span class='info'>";
                courseData += this.subscribersCount;
                courseData += " subscribors</span></h3><div class='startDate'><div class='startDateTop'><span>Start date</span><br /><span class='day'>";
                courseData += this.startDay;
                courseData += "</span></div><div class='startDateBottom'>";
                courseData += this.startMonth;
                courseData += "</div></div><div class='endDate' style='position: absolute;'><div class='endDateTop'><span>End date</span><br /><span class='day'>";
                courseData += this.endDay;
                courseData += "</span></div><div class='endDateBottom'>Oct</div></div><p>";
                courseData += this.information;
                courseData += "</p>";
                if (getCookie("UserId") != null) {
                    courseData += "<a class='subscribe'>Subscribe /<br/>Unsubscribe</a>";
                } else {
                    courseData += "<a class='subscribe' style='display: none;'>Subscribe /<br/>Unsubscribe</a>";
                }
                courseData += "<div class='clearfix'></div></article>";
                return courseData;
            }
        }

        _service.Subscription = function (course, subscriptionDate) {
            this.course = course;
            this.subscriptionDate = subscriptionDate;
            this.toString = function () {

            }
        }

        _service.getAllCourses = function (eventHandler) {
            var url = getUrl("Cources");

            $.ajax({
                type: "GET",
                timeout: _service.timeout,
                dataType: "json",
                url: url,
                success: function (data) {
                    eventHandler(data);
                }, fail: function (errorEvent) {
                    handleError(errorEvent);
                }
            });
        }

        _service.getTopCourses = function (count, eventHandler) {
            var url = getUrl("TopCources");
            var jsonData = JSON.stringify(count);

            $.ajax({
                type: "POST",
                timeout: _service.timeout,
                contentType: "application/json; charset=utf-8",
                url: url,
                data: jsonData,
                success: function (data) {
                    eventHandler(data);
                }, fail: function (errorEvent) {
                    handleError(errorEvent);
                }
            });
        }

        _service.getUserSubscriptions = function (userId, eventHandler) {
            var url = getUrl("MySubscriptions");
            var jsonData = JSON.stringify(userId);

            $.ajax({
                type: "POST",
                timeout: _service.timeout,
                contentType: "application/json; charset=utf-8",
                url: url,
                data: jsonData,
                success: function (data) {
                    eventHandler(data);
                }, fail: function (errorEvent) {
                    handleError(errorEvent);
                }
            });
        }

        _service.getCourses = function (skip, count, eventHandler) {
            var url = getUrl("Authenticate");
            var postData = '{"skip": "' + skip + '","count": "' + count + '"}';
            var jsonData = postData;

            $.ajax({
                type: "POST",
                timeout: _service.timeout,
                contentType: "application/json; charset=utf-8",
                url: url,
                data: jsonData,
                success: function (data) {
                    eventHandler(data);
                }, fail: function (errorEvent) {
                    handleError(errorEvent);
                }
            });
        }

        _service.getUserSubscriptions = function (userId, eventHandler) {
            var url = getUrl("MySubscriptions");
            var jsonData = JSON.stringify(userId);

            $.ajax({
                type: "POST",
                timeout: _service.timeout,
                contentType: "application/json; charset=utf-8",
                url: url,
                data: jsonData,
                success: function (data) {
                    eventHandler(data);
                }, fail: function (errorEvent) {
                    handleError(errorEvent);
                }
            });
        }

        _service.getUserCourses = function (userId, eventHandler) {
            var url = getUrl("MyCourses");
            var jsonData = JSON.stringify(userId);

            $.ajax({
                type: "POST",
                timeout: _service.timeout,
                contentType: "application/json; charset=utf-8",
                url: url,
                data: jsonData,
                success: function (data) {
                    eventHandler(data);
                }, fail: function (errorEvent) {
                    handleError(errorEvent);
                }
            });
        }

        _service.authenticate = function (username, password, eventHandler) {
            var url = getUrl("Authenticate");
            var postData = '{"username": "' + username + '","password": "' + password + '"}';
            var jsonData = postData;

            $.ajax({
                type: "POST",
                timeout: _service.timeout,
                contentType: "application/json; charset=utf-8",
                url: url,
                data: jsonData,
                success: function (data) {
                    eventHandler(data);
                }, fail: function (errorEvent) {
                    handleError(errorEvent);
                }
            });
        }

        _service.toggleSubscription = function (userId, courseId, eventHandler) {
            var url = getUrl("ToggleSubscription");
            var postData = '{"userId": "' + userId + '","courseId": "' + courseId + '"}';
            var jsonData = postData;

            $.ajax({
                type: "POST",
                timeout: _service.timeout,
                contentType: "application/json; charset=utf-8",
                url: url,
                data: jsonData,
                success: function (data) {
                    eventHandler(data);
                }, fail: function (errorEvent) {
                    handleError(errorEvent);
                }
            });
        }

        /* PRIVATE METHODS */
        function getUrl() {
            var url = serviceUrl;
            for (var i = 0; i < arguments.length; i++) {
                url += arguments[i];
                if (i < arguments.length - 1) {
                    url += "/";
                }
            }
            return url;
        }

        function handleError(errorEvent) {
            if (eventHandlers["error"] != undefined) {
                eventHandlers["error"](errorEvent);
            }
        }

        return _service;
    })();

    AcademySystemService.error(function (e) {
        showErrorDialog();
    });

    function loadAllCourses() {
        AcademySystemService.getAllCourses(function (data) {
            var courcesData = "<h2>All courses</h2>";
            var currentCourceData;
            for (var i = 0; i < data.length; i++) {
                currentCourceData = data[i];
                courcesData += createServiceCourse(currentCourceData).toString();
            }

            $("#articles").html(courcesData);
            $(".endDate").fadeTo(0, 0.01);
        });
    }

    function loadTopCourses() {
        AcademySystemService.getTopCourses(10, function (data) {
            var courcesData = "<h2>Top courses</h2>";
            var currentCourceData;
            for (var i = 0; i < data.length; i++) {
                currentCourceData = data[i];
                courcesData += createServiceCourse(currentCourceData).toString();
            }

            $("#articles").html(courcesData);
            $(".endDate").fadeTo(0, 0.01);
        });
    }

    function loadUserCourses() {
        AcademySystemService.getUserCourses(userId, function (data) {
            var courcesData = "<h2>User courses</h2>";
            var currentCourceData;
            for (var i = 0; i < data.length; i++) {
                currentCourceData = data[i];
                courcesData += createServiceCourse(currentCourceData).toString();
            }

            $("#articles").html(courcesData);
            $(".endDate").fadeTo(0, 0.01);
        });
    }

    function loadUserSubscriptions() {
        AcademySystemService.getUserSubscriptions(userId, function (data) {
            var courcesData = "<h2>User subscriptions</h2>";
            var currentCourceData;
            for (var i = 0; i < data.length; i++) {
                currentCourceData = data[i].Course;
                courcesData += createServiceCourse(currentCourceData).toString();
            }

            $("#articles").html(courcesData);
            $(".endDate").fadeTo(0, 0.01);
        });
    }

    function createServiceCourse(jsonCourse) {
        var courseData = new AcademySystemService.Cource(
            jsonCourse.CourseId,
            jsonCourse.Title,
            jsonCourse.Information,
            jsonCourse.SubscribersCount,
            jsonCourse.StartDay,
            jsonCourse.StartMonth,
            jsonCourse.EndDay,
            jsonCourse.EndMonth);
        return courseData;
    }

    /* LOADING DATA */
    if (currentPageIndex == 1) {
        loadTopCourses();
    } else if (currentPageIndex == 2) {
        loadAllCourses();
    } else if (currentPageIndex == 3) {
        loadUserCourses();
    } else if (currentPageIndex == 4) {
        loadUserSubscriptions();
    }

    /* LOGIN & LOGOUT*/
    $("#loginForm").keydown(function (e) {
        if (e.keyCode == 13) {
            authenticate();
        }
    });

    $("#loginSubmitButton").click(function () {
        authenticate();
    });

    $("#logout").click(function () {
        logout(false);
    });

    /* START & END DATE */
    $(".startDate").live("click", function () {
        var endDate = $(this).parent().find(".endDate");
        endDate.fadeTo(dateAnimationSpeed, 1);
        endDate.css("z-index", 1);

        $(this).fadeTo(dateAnimationSpeed, 0.01);
        $(this).css("z-index", 0);

    });

    $(".endDate").live("click", function () {
        var startDate = $(this).parent().find(".startDate");
        startDate.fadeTo(dateAnimationSpeed, 1);
        startDate.css("z-index", 1);

        $(this).fadeTo(dateAnimationSpeed, 0.01);
        $(this).css("z-index", 0);
    });

    $("#loginButton").click(function () {
        $(this).animate({
            marginTop: "-40px"
        }, globalAnimationSpeed);

        $("#loginForm").animate({
            top: "0px"
        }, globalAnimationSpeed);
    });

    $("#cancelButton").click(function () {
        hideLoginForm();
    });

    $(".subscribe").live("click", function () {
        var courseId = $(this).parent("article").attr("id");
        AcademySystemService.toggleSubscription(getCookie("UserId"), courseId, function (data) {

        });
    });

    function authenticate() {
        var username = $("#username").val();
        var password = $("#password").val();
        AcademySystemService.authenticate(username, password, function (data) {
            if (data.AuthenticateResult.IsAuthenticated) {
                login(data.AuthenticateResult.UserId, false);
            } else {
                loginFailed();
            }
        });
    }

    function login(userId, instant) {
        setCookie("UserId", userId, 30);
        $("#username").val("");
        $("#password").val("");
        if (instant) {
            $("#loginButton").fadeOut(0);
            $("#welcomeMessage").fadeIn(0);
            $("#menu").slideDown(0);
        } else {
            $("#loginButton").fadeOut(globalAnimationSpeed);
            $("#welcomeMessage").fadeIn(globalAnimationSpeed);
            $("#menu").slideDown(globalAnimationSpeed);
            hideLoginForm();
        }
        $(".subscribe").css("display", "inline");
    }

    function logout(instant) {
        deleteCookie("UserId");
        if (currentPageIndex > 1) {
            window.location = "index.html";
        } else {
            if (instant) {
                $("#loginButton").fadeIn(0);
                $("#welcomeMessage").fadeOut(0);
                $("#menu").slideUp(0);
            } else {
                $("#loginButton").fadeIn(globalAnimationSpeed);
                $("#welcomeMessage").fadeOut(globalAnimationSpeed);
                $("#menu").slideUp(globalAnimationSpeed);
            }
        }
        $(".subscribe").css("display", "none");
    }

    function loginFailed() {
        $("#loginFailed").slideDown(globalAnimationSpeed);
        setTimeout(function () {
            $("#loginFailed").slideUp(globalAnimationSpeed);
        }, 3000);
    }

    function hideLoginForm() {
        $("#loginForm").animate({
            top: "-160px"
        }, globalAnimationSpeed);

        $("#loginButton").animate({
            marginTop: "0px"
        }, globalAnimationSpeed);
    }

    function showErrorDialog() {
        var errorDialogSelector = "#errorDialog";
        $(errorDialogSelector).removeClass("hidden").dialog({
            buttons: {
                "Refresh": function () {
                    document.location.reload(true);
                }, "Cancel": function () {
                    $(this).dialog("close");
                }
            }, resizable: false,
            show: { effect: "slide", direction: "up" },
            hide: { effect: "slide", direction: "up" }
        });

        $(errorDialogSelector + " strong").click(function () { document.location.reload(true); });
    }

    /* COOKIES MANAGMENT */
    function setCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    function deleteCookie(name) {
        setCookie(name, "", -1);
    }
});






















